package org.devastra.arcinspect.core.data;

import java.util.regex.Pattern;

import org.devastra.arcinspect.core.data.cache.EntityInfoCache;


public class LibraryElementInfo extends AbstractEntityInfo {

	private static final Pattern SLASH = Pattern.compile("/");
	private static final int SLASH_STRING_LENGTH = 1;					//length of "/" character
	private static final int CLASS_SUFFIX_LENGTH = 6;					//length of ".class" suffix
	
	public LibraryElementInfo(String _qualName) {
		super(_qualName, EntityType.LIBRARY_ELEMENT, true);
	}

	public static EntityInfo getLibaryElement(String _libEntry) {
		EntityInfo elem = null;
		
		//the _libEntry is in one of the following forms
		// 1. org/w3c/tidy/
		// 2. org/w3c/tidy/Style.class
		//
		// Results in
		// ----------
		// Package: (org.xml.sax)
		// Element: Document
		
		//check in which pattern the name is
		//for folders
		//if(_libEntry.lastIndexOf('/') == _libEntry.length() - 1) {
		if(_libEntry.endsWith("/")) {
			//ignore the last '/'
			String packageName = SLASH.matcher(_libEntry.substring(0, _libEntry.length() - SLASH_STRING_LENGTH)).replaceAll(".");
			//elem = PackageInfo.getPackage(packageName);
			elem = EntityInfoCache.getEntityInfo(packageName);
			if(elem == null) {
				elem = new PackageInfo(packageName);
			} else if (!EntityType.PACKAGE.equals(elem.getType())) {
				elem = new PackageInfo(elem);
			}
			
		} else if (_libEntry.endsWith(".class")) { //only handle the class file
			//ignore the suffix '.class'
			/*
			int lastSlashPos = _libEntry.lastIndexOf('/');
			String packageName = SLASH.matcher(_libEntry.substring(0, lastSlashPos)).replaceAll(".");
			PackageInfo packageInfo = PackageInfo.getPackage(packageName);
			String elementName = _libEntry.substring(lastSlashPos + SLASH_STRING_LENGTH, _libEntry.length() - CLASS_SUFFIX_LENGTH);
			elem = new LibraryElementInfo(elementName, packageInfo.getId());
			*/
			
			String qualName = SLASH.matcher(_libEntry.substring(0, _libEntry.length() - CLASS_SUFFIX_LENGTH)).replaceAll(".");
			elem = new LibraryElementInfo(qualName);
		}
		
		return elem;
	}

}
